package com.xbn.xbnmall.cart.interceptor;

import com.xbn.common.constant.AuthServerConstant;
import com.xbn.common.constant.CartConstrant;
import com.xbn.common.vo.MemberRespVo;
import com.xbn.xbnmall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author XBN
 * @date 2020/8/14 15:48
 * @email 78742541@qq.com
 */
/*
* 拦截器，在执行目标方法执行判断有用户是否登陆
* */
@Component
public class CartInterceptor implements HandlerInterceptor {
    public static  ThreadLocal<UserInfoTo>  threadLocal=new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo=new UserInfoTo();
        HttpSession session=request.getSession();
        MemberRespVo member = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER_SESSION_KEY);
        if(member!=null)
        {
            //用户登录了
            userInfoTo.setUserId(member.getId());
        }

            //不管用户有没有登陆，都要尝试从cookie中获取临时用户的cookie
        //如果获取到了就会设置TempUser为true，拦截器后续就不会添加cookie了，如果没有获取到
        //拦截器后续就会添加一个
            Cookie[] cookies=request.getCookies();
            if(cookies!=null&&cookies.length>0)
            {
                for (Cookie cookie:cookies
                     ) {
                    String name=cookie.getName();
                    if(name.equals(CartConstrant.TEMP_USER_COOKIE_NAME))
                    {
                        userInfoTo.setUserKey(cookie.getValue());
                        userInfoTo.setTempUser(true);
                    }
                }
            }


        //如果当前没有临时/离线用户，我们就定义一个,在postHandle响应出去的时候添加到浏览器的响应中去
        if(StringUtils.isEmpty(userInfoTo.getUserKey()))
        {
            String uuid= UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);

        }
        threadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
      //判断是否存在了离线用户的cookie
        if(!threadLocal.get().isTempUser()) {
            Cookie cookie = new Cookie(CartConstrant.TEMP_USER_COOKIE_NAME, threadLocal.get().getUserKey());
            cookie.setDomain("xbnmall.com");
            cookie.setMaxAge(CartConstrant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
